import threading
import time
import random
import re
import datetime as dt
from urllib.parse import quote

import requests
from pyquery import PyQuery
import redis

from decrypt import decrypt

redis_cli = redis.Redis()

exitFlag = 0


class MyThread(threading.Thread):
    def __init__(self, proxies, uid):
        threading.Thread.__init__(self)
        self.proxies = proxies
        self.uid = uid

    def run(self):
        session = requests.session()
        if self.test_ip():
            try:
                do_vote('4396924', self.uid, session, self.proxies)
            except Exception:
                ...

    def test_ip(self):
        try:
            resp = requests.get('http://httpbin.org/get', proxies=self.proxies, timeout=3)
        except Exception as e:
            return None
        else:
            return resp.ok


def captcha_crack(content):
    resp = requests.post("http://192.168.0.52:7788", data=content)
    code = resp.json()["code"]
    return code


def do_vote(listid, uid, session, proxies=None):
    cookies = {
        'D5O_openinfos': quote(quote(f'{{"uid":"{uid}","token":""}}')),
    }

    headers = {
        'Host': 'h5.zhiyyuan.cn',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
        'Accept-Language': 'zh-cn',
        'Refer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
    }

    response = session.get(
        'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
        headers=headers,
        cookies=cookies,
        proxies=proxies,
        timeout=10)

    html = response.text
    # print(html)
    # print(response.ok)
    tokenVal = re.findall("tokenVal='(.*?)'", html)
    print(tokenVal)
    if not tokenVal:
        redis_cli.srem('success_uid', uid)
        return
    if tokenVal[0] == '':
        redis_cli.srem('success_uid', uid)
        return
    if dt.datetime.now().minute == 00 or dt.datetime.now().minute == 30:
        if redis_cli.sadd('vote_time', dt.datetime.now().strftime('%Y-%m-%d %H:%M:00')):
            doc = PyQuery(html)
            redis_cli.hset('votes_hd', f'{dt.datetime.now()}', f'{doc(".x_4397421").text()}')
            redis_cli.hset('votes_hy', f'{dt.datetime.now()}', f'{doc(".x_4396924").text()}')
            redis_cli.hset('votes_sg', f'{dt.datetime.now()}', f'{doc(".x_4735510").text()}')

    ouidVal = re.findall("ouidVal='(.*?)'", html)
    while 1:
        brandid = '1902857'
        idnum = brandid + listid
        zheng = ''
        idlength = 20 - len(idnum)

        for _ in range(idlength):
            zheng += str(round(random.random() * 9))

        rnd = f'{brandid}{listid}{zheng}'

        captcha_url = f'https://v.tiantianvote.com/api/c2/captchas.png.php?rnd={rnd}&type=2&id={listid}'

        # time.sleep(1)
        resp = session.get(captcha_url, proxies=proxies, timeout=10)
        # print(resp.ok)
        with open('vote.jpg', 'wb') as f:
            f.write(resp.content)
        pic_str = captcha_crack(resp.content)

        # captcha = input('输入验证码')

        captcha = (decrypt(pic_str)).strip()

        data = {
            'captcha': captcha,
            'rnd': rnd,
            'type': 2,
            'id': listid,
        }
        time.sleep(1)
        resp = session.post('https://v.tiantianvote.com/api/c2/captchas.check1.php', data=data, proxies=proxies,
                            timeout=10)
        print(resp.text)
        if re.search('﻿{"status":200,', resp.text):
            # print(captcha)
            break
        else:
            # time.sleep(random.randint(10, 60) * random.random())
            continue

    # print(captcha)
    data = {
        'brandid': brandid,
        'itemid': listid,
        'yqm': captcha,
        'rnd': rnd,
        'token': tokenVal[0],
        'ouid': uid,
        'sid': '0cf703fcd4add7d4',
    }
    time.sleep(1)

    headers_p = {
        'Host': 'v.tiantianvote.com',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin': 'https://h5.zhiyyuan.cn',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
        'Referer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
        'Accept-Language': 'zh-cn',
    }

    resp = requests.post('https://v.tiantianvote.com/v.php', data=data, headers=headers_p, proxies=proxies, timeout=10)
    print(resp.text)
    if re.search('"code":1,"msg":"success"', resp.text):
        redis_cli.sadd('success_uid', uid)
        redis_cli.sadd('success_uid_token', f'{uid}|{tokenVal[0]}')
        redis_cli.set(uid, 1, ex=1800)

    if re.search('{"code":11,"msg"', resp.text):
        redis_cli.srem('success_uid', uid)
    if re.search('{"code":6,"msg"', resp.text):
        ...
    return


def get_ip():
    params = {
        'apikey': '9eceff6b6002ffb5defcca8d8f6b00d52f53871e',
        'num': 30,
        'type': 'json',
        'line': 'win',
        'proxy_type': 'secret'
    }
    resp = requests.get('https://www.7yip.cn/api/', params=params)
    return resp.json()


def get_uid():
    success_uid_list = redis_cli.smembers('success_uid')
    uid_list = []
    for uid in success_uid_list:
        uid = uid.decode()
        if redis_cli.exists(uid):
            time.sleep(0.01)
            continue
        if uid not in uid_list:
            uid_list.append(uid)
        if len(uid_list) == 10:
            break
    for i in range(30 - len(uid_list)):
        uid = redis_cli.get('start_uid2').decode()
        uid_list.append(uid)
        redis_cli.incrby('start_uid2')

    return uid_list


def main():
    try:
        ip_list = get_ip()
    except Exception:
        ...
    else:
        t_list = []

        uid_list = get_uid()

        for ip in ip_list:
            proxies = {
                'http': f'http://{ip}',
                'https': f'https://{ip}'
            }
            uid = uid_list.pop()
            t_list.append(MyThread(proxies, uid))

        for t in t_list:
            t.start()

        for t in t_list:
            t.join()


if __name__ == '__main__':
    while 1:
        _7_clock = dt.datetime.strptime(dt.datetime.now().strftime('%Y-%m-%d 07:00:00'), '%Y-%m-%d %H:%M:%S')
        _24_clock = dt.datetime.strptime(dt.datetime.now().strftime('%Y-%m-%d 23:59:59'), '%Y-%m-%d %H:%M:%S')
        now = dt.datetime.now()

        if _7_clock < dt.datetime.now() < _24_clock:
            s = time.time()
            main()
            e = time.time()
            print(e - s)

        time.sleep(1)
